package com.qd.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.pay.domain.OrderReportNotifyLogDTO;
import com.qd.pay.model.OrderReportNotifyLog;
import com.qd.pay.repository.OrderReportNotifyLogRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderReportNotifyLogService {

    private final OrderReportNotifyLogRepository orderReportNotifyLogRepository;
    @Resource
    private RedisTemplateUtil<OrderReportNotifyLog> redisTemplateUtil;

    private static final String PREFIX_ID = "m_order_report_notify_log_logid_{0}";

    @Transactional(rollbackFor = Exception.class)
    public OrderReportNotifyLog save(OrderReportNotifyLog model) throws ApiException {
        try {
            if (!orderReportNotifyLogRepository.save(model)) {
                throw new ApiException(ApiResult.error());
            }
            return model;
        } finally {
            clearCache(model);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(OrderReportNotifyLog model) throws ApiException {
        final OrderReportNotifyLog historyModel = Optional.ofNullable(getById(model.getLogid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        try {
            if (!orderReportNotifyLogRepository.updateById(model)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean removeById(String logId) throws ApiException {
        final OrderReportNotifyLog historyModel = Optional.ofNullable(getById(logId)).orElseThrow(() -> new ApiException("ID不存在,不能删除"));
        try {
            if (!orderReportNotifyLogRepository.removeById(logId)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    public Boolean isExists(String logId) {
        return orderReportNotifyLogRepository.isExists(logId);
    }

    public OrderReportNotifyLog getById(String logId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, logId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY * 3), () -> orderReportNotifyLogRepository.getById(logId), OrderReportNotifyLog.class);
    }

    public IPage<OrderReportNotifyLogDTO> page(Page<OrderReportNotifyLogDTO> page, OrderReportNotifyLog model) {
        QueryWrapper<OrderReportNotifyLog> queryWrapper = new QueryWrapper<>(model);
        IPage<OrderReportNotifyLog> iPage = orderReportNotifyLogRepository.page(page.convert(this::dtoToModel), queryWrapper);
        return iPage.convert(this::modelToDto);
    }


    private void clearCache(OrderReportNotifyLog model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLogid());
        redisTemplateUtil.deleteByKey(key);
    }

    public OrderReportNotifyLogDTO modelToDto(OrderReportNotifyLog model) {
        if (null == model) {
            return null;
        }
        OrderReportNotifyLogDTO dto = new OrderReportNotifyLogDTO();
        dto.setLogid(model.getLogid());
        dto.setNotifyTime(model.getNotifyTime());
        dto.setLogTime(model.getLogTime());
        dto.setNotifyUrl(model.getNotifyUrl());
        dto.setNotifyBody(model.getNotifyBody());
        dto.setSfcg(model.getSfcg());
        dto.setOrderId(model.getOrderId());
        model.freeData();
        return dto;
    }

    public OrderReportNotifyLog dtoToModel(OrderReportNotifyLogDTO dto) {
        if (null == dto) {
            return null;
        }
        OrderReportNotifyLog model = new OrderReportNotifyLog();
        model.setLogid(dto.getLogid());
        model.setNotifyTime(dto.getNotifyTime());
        model.setLogTime(dto.getLogTime());
        model.setNotifyUrl(dto.getNotifyUrl());
        model.setNotifyBody(dto.getNotifyBody());
        model.setSfcg(dto.getSfcg());
        model.setOrderId(dto.getOrderId());
        dto.freeData();
        return model;
    }

}